package com.bawei.lib_cache.mmkv

import com.baway.cache.ICache
import com.bawei.lib_base.BaseApp
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/**
 * 使用mmkv来实现
 * 注意事项:1.MMKV支持跨进程间访问的(MULTI_PROCESS_MODE)
 * 2支持设置过期时间和数据加密
 * 3.采用内存映射方式(mmap)来实现的,访问效率高
 */
object KVmmkvCache: ICache {
    private val cryptkey="video_mmkv_crypt_key"
    private val expireTime=7*24*60*60//7天

    init {
        //初始化
     MMKV.initialize(BaseApp.appContext)

    }
    override fun putString(key: String, value: String) {
       MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey).encode(key,value, expireTime)
    }

    override fun putInt(key: String, value: Int) {
        MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey).encode(key,value, expireTime)
    }

    override fun putLong(key: String, value: Long) {
        MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey).encode(key,value, expireTime)
    }

    override fun putBool(key: String, value: Boolean) {
        MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey).encode(key,value, expireTime)
    }

    override fun getString(key: String): Flow<String> {
      return  flow {
          MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey)?.decodeString(key,"",)!!
      }
    }

    override fun getInt(key: String): Flow<Int> {
        return  flow {
            MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey)?.decodeInt(key,0)!!
        }
    }

    override fun getLong(key: String): Flow<Long> {
        return  flow {
            MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey)?.decodeLong(key,0)!!
        }
    }

    override fun getBool(key: String): Flow<Boolean> {
        return  flow {
            MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptkey)?.decodeBool(key,false)!!
        }
    }
}